package com.zhongdu.stady.shiro.realm;

import com.zhongdu.stady.pojo.User;
import com.zhongdu.stady.shiro.ELoginType;
import com.zhongdu.stady.token.PhoneToken;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

/**
 * @ClassNameUsernameRealm
 * @Description
 * @Author ange
 * @Date2019/10/17 14:45
 * @Version V1.0
 **/
@Slf4j
public class UsernameRealm extends AuthorizingRealm {
    /**
     * 授权方法
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    /**
     * 验证方法
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        log.info("---------------- 用户密码登录 ----------------------");
        UsernamePasswordToken authcToken = (UsernamePasswordToken) token;
        String name = authcToken.getUsername();
        if (name.equals("zhangsan") && String.valueOf(authcToken.getPassword()).equals("123456") ) {
            User user = new User();
            user.setUsername(name);
            user.setPassword(String.valueOf(authcToken.getPassword()));
            SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                    user, //用户
                    user.getPassword(), //密码
                    getName()  //realm name
            );
            return authenticationInfo;
        }
        return null;
    }

    @Override
    public String getName() {
        return ELoginType.USERNAME.getType();
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        if (token instanceof PhoneToken) {
            return ((PhoneToken) token).getLoginType() == ELoginType.USERNAME;
        } else {
            return false;
        }
    }
}